package com.hjf.booking.security.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author hjf
 * @date 2021-03-25 15:48
 */
public class JwtUtil {

    public static final String salt = "key-test-0101";

    private static final byte[] SECRET = "6MNSobBRCHGIO0fS6MNSobBRCHGIO0fS".getBytes();

    public static String buildJwt(String username){

        Algorithm algorithm = Algorithm.HMAC256(salt);
        Date date = new Date(System.currentTimeMillis()+3600*100);

        return JWT.create()
                .withIssuer(username)
                .withSubject(username)
                .withExpiresAt(date)
                .withIssuedAt(new Date())
                .sign(algorithm);
    }

    public static String decodJwt(String token) {
        DecodedJWT jwt = JWT.decode(token);
        try {
            Algorithm algorithm = Algorithm.HMAC256(salt);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            System.out.println(decodedJWT);
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        }
        String username = jwt.getSubject();
        System.out.println(username);
        return jwt.toString();
    }

}
